package com.settlement.system.controller;

import com.settlement.system.csv.CsvExportBuilder;
import com.settlement.system.csv.CsvExportUtil;
import com.settlement.system.common.enums.ExcelFileType;
import com.settlement.system.model.entity.common.TblMarketToolBillDetail;
import com.settlement.system.model.entity.common.TblReceiveRefundShop;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.*;
import com.settlement.system.service.csv.DateSpiltCsvDatas;
import com.settlement.system.common.util.common.FasUtil;
import com.alibaba.excel.context.AnalysisContext;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 营销工具原始账单 前端控制器
 * @author xiaochuan
 * @since 2022-12-21
 */

@Slf4j
@Api(tags = "营销工具原始账单",description = "营销工具原始账单")
@RestController
@RequestMapping("/tblMarketToolBillDetail")
public class TblMarketToolBillDetailController extends ExcelController<TblMarketToolBillDetail> {

    @Value("${system.export-root.path}")
    private String exportRootPath;

    @Resource
    private ITblMarketToolBillDetailService tblMarketToolBillDetailService;

    @Resource
    private ITblRrBillTypeService tblRrBillTypeService;

    @Resource
    private ITblRrChannelService tblRrChannelService;

    @Resource
    private ITblReceiveRefundShopService tblReceiveRefundShopService;

    @Override
    public IBaseService init() {
        return tblMarketToolBillDetailService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblMarketToolBillDetail.class;
    }


    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model, "channelNo","billType","ncShopNo");
        super.setParamsModel(model);
    }

    public String checkSaveModel(TblMarketToolBillDetail detail){
        try{
            {
                String billType = detail.getBillType();
                String billTypeNo = tblRrBillTypeService.getNoByName(billType);
                if(StringUtils.isEmpty(billTypeNo)){
                    return "[账单类型]必须在【RR-账单类型】存在“账单类型”，请确认后导入";
                }
                detail.setBillType(billTypeNo);

                String noByName = tblRrChannelService.getNoByName(detail.getChannelName());
                if(StringUtils.isEmpty(noByName)){
                    return "[平台]必须是在【RR-渠道设置】存在的“渠道名称”，请确认后导入";
                }
                detail.setChannelNo(noByName);

                TblReceiveRefundShop shop = tblReceiveRefundShopService.getByNcShopNo(detail.getNcShopNo());
                if (shop == null) {
                    return "导入的“NC_辅助项_店铺”不是【RR-店铺设置】存在的“NC店铺名称”，请校验";
                }
                detail.setNcShopName(shop.getNcShopName());
            }

            List<TblMarketToolBillDetail> tblRrRecordProjectMains = tblMarketToolBillDetailService.selectByParams(detail);
            if(!CollectionUtils.isEmpty(tblRrRecordProjectMains)){
                return "数据已存在";
            }
        } catch (Exception e) {
            log.error("校验时查询出错",e);
            return "校验时查询出错";
        }
        return null;
    }

    @Override
    public String verifyImportObject(TblMarketToolBillDetail tblMarketToolBillDetail, AnalysisContext analysisContext) {

        String message = super.verifyImportObject(tblMarketToolBillDetail,analysisContext);
        if(StringUtils.isNotEmpty(message)){
            return message;
        }
        message = checkSaveModel(tblMarketToolBillDetail);
        if (StringUtils.isNotEmpty(message)) {
            return message;
        }

        return super.verifyImportObject(tblMarketToolBillDetail, analysisContext);
    }

    @Override
    protected String validateAllDate(List<TblMarketToolBillDetail> datas) {
        List<String> list = new ArrayList<>();
        for(TblMarketToolBillDetail data : datas){
            String toString = data.toString();
            if(list.contains(toString)){
                return "有两行数据重复";
            }else{
                list.add(toString);
            }
        }

        return super.validateAllDate(datas);
    }


    @Override
    public ObjectDataResponse importFile(MultipartFile file, HttpServletRequest request) {
        return super.importFile(file, request);
    }

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> params = buildParam(request);
        setParamsModel(params);
        Object fileName = "营销工具原始账单";
        String path = exportRootPath + System.currentTimeMillis() + File.separator;
        CsvExportUtil.createCsv()
                .headClass(TblMarketToolBillDetail.class)
                .fileName(fileName.toString())
                .fileType(ExcelFileType.XLSX)
                .model(CsvExportBuilder.MULTI_ZIP_MODEL)
                .parentPath(path)
                .csvDatas(new DateSpiltCsvDatas(tblMarketToolBillDetailService, params))
                .export(request, response);
    }

    @Override
    public void exportExcelPost(HttpServletRequest request, HttpServletResponse response,@RequestBody Map<String, Object> params) throws Exception {
        setParamsModel(params);
        String fileName = "营销工具原始账单";
        String path = exportRootPath + System.currentTimeMillis() + File.separator;
        CsvExportUtil.createCsv()
                .headClass(TblMarketToolBillDetail.class)
                .fileName(fileName)
                .fileType(ExcelFileType.XLSX)
                .model(CsvExportBuilder.MULTI_ZIP_MODEL)
                .parentPath(path)
                .csvDatas(new DateSpiltCsvDatas(tblMarketToolBillDetailService, params))
                .export(request, response);
    }
}

